import { Radio, RadioChangeEvent, Spin, type DatePickerProps } from 'antd';
import dayjs from 'dayjs';
import React, { useEffect, useRef, useState } from 'react';

import EchartsComponent, { MyChartOption } from '@/components/EchartsComponent';
import type { ProColumns, ProFormInstance } from '@/components/Pro/';
import { ProTable } from '@/components/Pro/';
import { getEmptyOptions, getTimeType } from '@/dictionary';
import { statisticElectricityControllerGenerateDayReportGraph } from '@/services/ess/statisticElectricity';
import {
  strategyTrackControllerGetStrategyExecuteList as getList,
  strategyTrackControllerGetStrategyExecuteTotal as getTotal,
} from '@/services/ess/strategyTrack';
import { useIntl, useModel } from 'umi';
import ChartForm from './ChartForm';
import IncomeChart from './IncomeChart';
import SocChart from './SocChart';
import styles from './strategy.less';

export const OverviewOfStrategyExecution: React.FC = ({ areaList }) => {
  const intl = useIntl();
  const formRef = useRef<ProFormInstance>();
  // 合计：收益等
  const [total, setTotal] = useState<API.StatisticStrategyExecDto>();
  const { isArea } = useModel('@@initialState')?.initialState || {};
  const [dataCount, setDataCount] = useState<number>();
  const [showType, setShowType] = useState('1');
  const [chartLoading, setChartLoading] = useState(false);
  const chartRef = useRef(null);
  const [options, setOptions] = useState<MyChartOption>({});

  useEffect(() => {
    formRef?.current?.setFieldValue('areaId', areaList?.[0]?.value);
    formRef?.current?.submit();
  }, [areaList]);

  const disabledDate: DatePickerProps['disabledDate'] = (current, { from }) => {
    const disabled = current > dayjs();

    if (from) {
      return disabled || Math.abs(current.diff(from, 'days')) >= 30;
    }

    return disabled;
  };

  const columns: ProColumns[] = [
    {
      title: intl.formatMessage({
        id: 'global.s/N',
      }),
      dataIndex: 'pageIndex',
      hideInSearch: true,
    },
    {
      title: intl.formatMessage({
        id: 'global.area',
      }),
      dataIndex: 'areaId',
      order: 200,
      valueType: 'select',
      initialValue: areaList?.[0]?.value,
      fieldProps: {
        options: areaList,
        allowClear: false,
      },
      hideInTable: !isArea,
      hideInSearch: !isArea,
      render: (_, record) => record.areaName,
    },
    {
      title: intl.formatMessage({
        id: 'global.date',
      }),
      dataIndex: 'date',
      hideInSearch: true,
    },
    {
      title: intl.formatMessage({
        id: 'global.date',
      }),
      dataIndex: 'date',
      hideInTable: true,
      // search field
      initialValue: [dayjs().subtract(6, 'day'), dayjs()],
      valueType: 'dateRange',
      fieldProps: {
        disabledDate: disabledDate,
        allowClear: false,
      },
      search: {
        transform: (value) => {
          if (value) {
            return {
              startDate: value[0],
              endDate: value[1],
            };
          }
        },
      },
    } satisfies ProColumns<any, 'dateRange'>,
    {
      title: intl.formatMessage({
        id: 'strategyControl.strategyTracking.timePeriod',
      }),
      dataIndex: 'startTime',
      render: (_, record) => `${record.startTime} - ${record.endTime}`,
      hideInSearch: true,
    },
    {
      title: intl.formatMessage({
        id: 'strategyControl.strategyTracking.timePeriodType',
      }),
      dataIndex: 'timeType',
      valueEnum: getTimeType(),
      hideInSearch: true,
    },
    {
      title: intl.formatMessage({
        id: 'strategyControl.strategyTracking.electricityPrice',
      }),
      dataIndex: 'fee',
      hideInSearch: true,
    },
    {
      title: `${intl.formatMessage({
        id: 'strategyControl.strategyTracking.actualChargingCapacity',
      })}(kWh)`,
      dataIndex: 'chargeCapacity',
      hideInSearch: true,
    },
    {
      title: `${intl.formatMessage({
        id: 'strategyControl.strategyTracking.actualDischargeCapacity',
      })}(kWh)`,
      dataIndex: 'dischargeCapacity',
      hideInSearch: true,
    },

    {
      title: intl.formatMessage({
        id: 'strategyControl.strategyTracking.revenue',
      }),
      dataIndex: 'income',
      hideInSearch: true,
    },
    {
      title: intl.formatMessage({
        id: 'strategyControl.strategyTracking.socStart',
      }),
      dataIndex: 'startSoc',
      hideInSearch: true,
    },
    {
      title: intl.formatMessage({
        id: 'strategyControl.strategyTracking.socEnd',
      }),
      dataIndex: 'endSoc',
      hideInSearch: true,
    },
  ];

  const submitForm = (value: any) => {
    if (options) {
      setChartLoading(true);
    }

    const params = {
      areaFlag: value.areaFlag ?? false,
      date: dayjs(value.date).format('YYYY-MM-DD'),
      codes: Array.isArray(value?.code) ? value.code : value?.code ? [value.code] : undefined,
    };

    statisticElectricityControllerGenerateDayReportGraph(params)
      .then((res) => {
        if (res.success && res.data) {
          // 清除旧图表
          chartRef?.current?.instance()?.clear();

          // 构建新的图表配置
          const newOptions = {
            tooltip: {
              trigger: 'axis',
              axisPointer: {
                type: 'shadow',
              },
            },
            legend: {
              type: 'scroll',
              width: '80%',
              top: 20,
              right: 0,
              icon: 'rect',
            },
            grid: {
              left: '3%',
              right: '4%',
              bottom: '3%',
              containLabel: true,
            },
            xAxis: [
              {
                type: 'category',
                data: res.data.xaxis, // 直接使用原始时间数据
                axisTick: {
                  alignWithLabel: true,
                },
                axisLabel: {
                  formatter: function (params: string) {
                    return params.split(':')[0]; // 只显示小时
                  },
                },
              },
            ],
            yAxis: [
              {
                name: intl.formatMessage({ id: 'statistics.common.unitkWh' }),
                type: 'value',
                axisLine: {
                  show: true,
                },
              },
            ],
            series:
              res.data.yaxis
                ?.sort((a, b) => (a.deviceName ?? '').localeCompare(b.deviceName ?? ''))
                .map((item) => {
                  // 直接从 points 中获取 yaxis 值
                  const data = item.points.map((point) => point.yaxis ?? 0);

                  return {
                    type: 'bar',
                    name: item.deviceName + '-' + item.title, // 设备名称 + 标题
                    stack: item.deviceName, // 使用设备名称作为堆叠标识
                    itemStyle: {
                      color: item.title?.includes(
                        intl.formatMessage({ id: 'statistics.work.discharge' }),
                      )
                        ? '#1A6CFE' // 放电量颜色
                        : '#67C23A', // 充电量颜色
                    },
                    barWidth: '20%',
                    data: data,
                  };
                }) || [],
          };

          // 设置新的图表配置
          setOptions(newOptions);
          setChartLoading(false);
        } else {
          // 处理空数据情况
          if (chartRef?.current?.instance()) {
            chartRef?.current?.instance().clear();
          }
          setOptions(getEmptyOptions());
          setChartLoading(false);
        }
      })
      .catch(() => {
        setChartLoading(false);
      });
  };

  return (
    <div style={{ position: 'relative' }}>
      <div
        style={{
          position: 'absolute',
          right: 0,
          top: 10,
          width: showType === '1' ? 'auto' : '100%',
          display: 'flex',
          justifyContent: showType === '1' ? 'flex-end' : 'space-between',
          zIndex: 2,
        }}
      >
        {showType === '2' && <ChartForm dateType={'date'} submitForm={submitForm} />}
        <Radio.Group
          value={showType}
          buttonStyle="solid"
          onChange={(e: RadioChangeEvent) => {
            setShowType(e.target.value);
          }}
          size="middle"
        >
          <Radio.Button value="1" style={{ height: 32, lineHeight: '32px' }}>
            {intl.formatMessage({ id: 'statistics.common.list' })}
          </Radio.Button>
          <Radio.Button value="2" style={{ height: 32, lineHeight: '32px' }}>
            {intl.formatMessage({ id: 'statistics.common.chart' })}
          </Radio.Button>
        </Radio.Group>
      </div>
      {showType === '1' && (
        <ProTable<
          API.StatisticStrategyExecDto,
          API.strategyTrackControllerGetStrategyExecuteListParams
        >
          formRef={formRef}
          rowKey={(record) => `${record.date}${record.startTime}${record.endTime}`}
          columns={columns}
          // search={{
          //   span: { xs: 24, sm: 24, md: 12, lg: 12, xl: 12, xxl: 7 },
          // }}
          request={async (params) => {
            if (isArea && !params?.areaId) {
              return;
            }
            try {
              const { data } = await getTotal({
                startDate: params.startDate,
                endDate: params.endDate,
                areaId: params.areaId,
              });
              setTotal(data);
            } catch (error) {}

            const response = await getList(params);
            setDataCount(Number(response.data?.total));

            // table 有个隐含行为，response.data 里有 records，它会加上pageIndex字段
            return response;
          }}
          footer={
            !dataCount
              ? undefined
              : () => {
                  const { chargeCapacity, dischargeCapacity, income } = total ?? {};
                  return (
                    <div style={{ display: 'flex', alignItems: 'center', gap: 20 }}>
                      <div style={{ flex: 1 }}>
                        {intl.formatMessage({
                          id: 'global.total',
                        })}
                      </div>
                      <div>
                        {intl.formatMessage({
                          id: 'strategyControl.strategyTracking.totalCharge',
                        })}
                        ：{chargeCapacity ?? '--'}
                      </div>
                      <div>
                        {intl.formatMessage({
                          id: 'strategyControl.strategyTracking.totalDischarge',
                        })}
                        ：{dischargeCapacity ?? '--'}
                      </div>
                      <div>
                        {intl.formatMessage({
                          id: 'strategyControl.strategyTracking.totalRevenue',
                        })}
                        ：{income ?? '--'}
                      </div>
                    </div>
                  );
                }
          }
        />
      )}
      {showType === '2' && (
        <div style={{ height: '100%', paddingTop: 60 }}>
          <div className="flex flex-col">
            <p className={styles.strategyTitle}>充放电量</p>
            <Spin spinning={chartLoading}>
              <EchartsComponent option={options} height={340} ref={chartRef} />
            </Spin>
          </div>
          <div className={styles.strategyBar}></div>
          <div className="flex flex-col" style={{ paddingTop: 30 }}>
            <p className={styles.strategyTitle}>电价差收益</p>
            <IncomeChart height={340} />
          </div>
          <div className={styles.strategyBar}></div>
          <div className="flex flex-col" style={{ paddingTop: 30 }}>
            <p className={styles.strategyTitle}>SOC曲线</p>
            <SocChart height={340} />
          </div>
        </div>
      )}
    </div>
  );
};
